#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <fat.h>

#include "game.h"

#include "menu_png.h"
#include "logo_png.h"

using namespace std;


Game::Game(GRRLIB_texImg *Font): mapLen(0), PrintConsole(false), Alpha(10), CountUp(true) {
	// Create map
	map = new Map();
	
	mapLen = map->GetLength();
	
	// Create player
	mario = new Player(mapLen);
	
	texMenu = GRRLIB_LoadTexture(menu_png);
	if(texFont)
		texFont = Font;
}

Game::~Game() {
	delete map;
	delete mario;
	
	GRRLIB_FreeTexture(texMenu);
}
	
void Game::Menu() {
	if(WPAD_ButtonsDown(0) & WPAD_BUTTON_PLUS)
		PrintConsole = !PrintConsole;
	
	GRRLIB_DrawImg (0, 0, texMenu, 0, 1, 1, GRRLIB_WHITE);
	
	PrintPressAMsg();
}

void Game::Play() {
	if(WPAD_ButtonsDown(0) & WPAD_BUTTON_PLUS)
		PrintConsole = !PrintConsole;
		
	// Move player
	mario->Move();
	
	// Move Bg
	ScrollBG(mario, mapLen);
	
	// Draw Bg
	map->Draw(*mario);
	// Draw player
	mario->Draw();
	
	GRRLIB_Printf(6, 22, texFont, GRRLIB_WHITE, 1, "Coins: %d", map->GetCoins());
}

bool Game::ConsoleEnabled() {
	return PrintConsole;
}
	
void Game::ScrollBG(Player *pl, int len) {
	if(((fix_norm(pl->GetX()-pl->GetScroll())) > 480) && (fix_norm(pl->GetX()) < len-200)) { // Scroll more...
		pl->SetScroll(pl->GetX() - norm_fix(480));		
	}
	else if((((pl->GetX()-pl->GetScroll())>>8) < 100) && ((pl->GetX()>>8) > 100)) {
		pl->SetScroll(pl->GetX() - norm_fix(100));		
	}
}

void Game::Splashscreen(void) {
	// Black bg
	GRRLIB_SetBackgroundColour(0, 0, 0, 255);
	GRRLIB_texImg *texLogo = GRRLIB_LoadTexture(logo_png);
	
	for(int i = 1; i < 250; i += 4) {
		GRRLIB_DrawImg (0, 0, texLogo, 0, 1, 1, RGBA(255, 255, 255, i));
		GRRLIB_Render();
	}
	
	for(int i = 0; i < 50; i++) {
		GRRLIB_DrawImg (0, 0, texLogo, 0, 1, 1, GRRLIB_WHITE);
		GRRLIB_Render();
	}
	
	for(int i = 255; i > 20; i -= 4) {
		GRRLIB_DrawImg (0, 0, texLogo, 0, 1, 1, RGBA(255, 255, 255, i));
		GRRLIB_Render();
	}
	GRRLIB_DrawImg (0, 0, texLogo, 0, 1, 1, RGBA(255, 255, 255, 0));
	GRRLIB_Render();
		
	GRRLIB_FreeTexture(texLogo);
}

void Game::PrintPressAMsg() {
	GRRLIB_Printf(220, 375, texFont, RGBA(1, 1, 1, Alpha), 1, "Press A to start...");
	if(CountUp) {
		Alpha += 2;
		if(Alpha > 252) 
			CountUp = false;
	} else {
		Alpha -= 2;
		if(Alpha < 12) 
			CountUp = true;
	}
}
